from django.http import JsonResponse
from django.views import View
import json
from . import models

class Tutor(View):
    ###添加数据
    def post(self, request):
        data = json.loads(request.body)
        tutor = models.Tutor.objects.create(
            name = data['name'],
            age = data['age'],
            sex = data['sex']
        )
        course = models.Course.objects.create(
            name = data['course'].get('name'),
            credit = data['course'].get('credit'),
        )
        tutor.course_list.add(course)
        response = {
            "tutor_id":tutor.id,
            "course_id":course.id,
        }
        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})

    ###获取数据
    def get(self,request):
        name = json.loads(request.body)['name']
        courses = models.Course.objects.filter(tutor__name=name).all()
        courses_name = []
        for course in courses:
            courses_name.append(course.name)
        response = {
            "tutor_name":name,
            "courses_list":courses_name,
        }
        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})

    ###删除数据
    def delete(self,request):
        name = json.loads(request.body)['name']
        del_tutor = models.Tutor.objects.filter(name=name).first()
        del_id = del_tutor.id
        del_tutor.delete()
        response = {
            "del_tutor_id":del_id,
        }
        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})

    ###修改数据
    def put(self,request):
        data = json.loads(request.body)
        course_name = data['course_name']
        credit = data['new_credit']
        courses = models.Course.objects.filter(name=course_name)
        count = 0
        for course in courses:
            count += 1
            course.credit = credit
            course.save()
        response = {
            "update_count":count
        }
        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})